package tech.mhuang.pacebox.springboot.core.protocol.tree;

import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.data.BaseTreeNode;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 树节点工具类
 *
 * @author mhuang
 * @since 1.1.2
 */
public class TreeNodeUtil {

    /**
     * 将当前列表数据转成封装成树状图数据
     *
     * @param nodeList 列表数据
     * @return 树状图数据
     */
    public static List<BaseTreeNode> assembleTree(List<BaseTreeNode> nodeList) {
        if (CollectionUtil.isEmpty(nodeList)) {
            return null;
        }
        List<BaseTreeNode> rstList = nodeList.stream().filter(node -> StringUtil.isEmpty(node.getParentId())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(rstList)) {
            return null;
        }
        rstList.stream().forEach(rst -> assembleTree(rst, nodeList));

        return rstList;
    }

    /**
     * 根据id将树列表封装成树状图数据
     *
     * @param id       树id
     * @param nodeList 树列表
     * @return 树状图数据
     */
    public static BaseTreeNode assembleTree(String id, List<BaseTreeNode> nodeList) {
        if (CollectionUtil.isEmpty(nodeList)) {
            return null;
        }
        Optional<BaseTreeNode> optionalBaseTreeNode = nodeList.stream().filter(node -> id.equals(node.getId())).findAny();

        if (optionalBaseTreeNode.isPresent()) {
            return assembleTree(optionalBaseTreeNode.get(), nodeList);
        } else {
            return null;
        }
    }

    /**
     * 根据某个节点将树列表封装成树状图数据
     *
     * @param node     树节点
     * @param nodeList 树列表
     * @return 树状图数据
     */
    public static BaseTreeNode assembleTree(BaseTreeNode node, final List<BaseTreeNode> nodeList) {
        if (CollectionUtil.isEmpty(nodeList)) {
            return node;
        }

        List<BaseTreeNode> childrenList = nodeList.stream()
                .filter(children -> StringUtil.equals(node.getId(), children.getParentId()))
                .collect(Collectors.toList());

        childrenList.forEach(children -> assembleTree(children, nodeList));
        node.setChildren(childrenList);

        return node;
    }
}
